package com.example.coolweatherreview.service;

import java.net.URLEncoder;
import java.util.prefs.Preferences;

import com.example.coolweatherreview.receiver.AutoUpdateReceiver;
import com.example.coolweatherreview.util.HttpCallbackListener;
import com.example.coolweatherreview.util.HttpUtil;
import com.example.coolweatherreview.util.Utility;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;

public class AutoUpdateService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				updateWeather();
			}

		}).start();
		
		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
		int anHour = 60*60*1000;
		long triggerTime = SystemClock.elapsedRealtime()+anHour;
		Intent i = new Intent(this,AutoUpdateReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
		manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pi);
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 更新天气信息
	 */
	private void updateWeather() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String cityName = prefs.getString("city_name", "");
		String API = "https://free-api.heweather.com/v5/";
		String KEY = "df60be951e0e4b8aa09e3b3ccd00c5b2";
		String address = API +"weather?city="+convertCode(cityName)+"&key=" + KEY;	
		
		HttpUtil.setHttpRequest(address, new HttpCallbackListener() {
			
			@Override
			public void onFinish(String response) {
				Utility.handleWeatherResponse(AutoUpdateService.this, response);
			}
			
			@Override
			public void onError(Exception e) {
				e.printStackTrace();
			}
		});
	}
	
	/**
	 * 转码*/
	private static  String convertCode(String str){
		try {
			String convert = URLEncoder.encode(str,"utf-8");
			return convert;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
